﻿#include "UploadFileRequest3Private.h"
#include "ZFtpUtils.h"
#include "UploadFileResponse3Private.h"
#include <QTextCodec>

BEGIN_NAMESPACE_ZFTPNS

UploadFileRequest3Private::UploadFileRequest3Private(QObject *parent)
    : ZFtpRequestPrivate(parent),
      q_ptr(NULL),
      m_task_id(-1)
{

}

UploadFileRequest3Private::~UploadFileRequest3Private()
{
    // 关闭文件
    if (m_file.isOpen())
        m_file.close();
}

int UploadFileRequest3Private::commandID() const
{
    return ZFtpRequestPrivate::PutV3;
}

int UploadFileRequest3Private::doRequest(QSharedPointer<QFtp> ftp, QSharedPointer<ZFtpConfig> cfg)
{
    if (!ftp)
    {
        m_task_id = -1;
    }
    else
    {
        ftp->disconnect(this);
        connect(ftp.data(), SIGNAL(commandFinished(int,bool)), SLOT(slotCommandFinished(int,bool)));

        if (cfg)
        {
            // 进行编码转换，防止中文乱码
            QTextCodec *text_codec = cfg->ftpServerTextCodec();

            // QString直接包裹指定编码的数据
            QString coded_ftp_filepath = ZFtpUtils::toTextCodecString(text_codec, m_ftp_filepath);

            // 关闭文件
            if (m_file.isOpen())
                m_file.close();

            m_file.setFileName(m_local_filepath);
            if (!m_file.open(QFile::ReadOnly))
            {
                m_task_id = -1;
            }
            else
            {
                m_task_id = ftp->put(&m_file, coded_ftp_filepath);
            }
        }
        else
        {
            m_task_id = ftp->put(&m_file, m_ftp_filepath);
        }
    }

    return m_task_id;
}

QPointer<ZFtpRequest> UploadFileRequest3Private::publicObject()
{
    return QPointer<ZFtpRequest>(q_ptr);
}

ZFtpResponsePrivate *UploadFileRequest3Private::createResponse()
{
    return new UploadFileResponse3Private();
}

void UploadFileRequest3Private::slotCommandFinished(int id, bool error)
{
    Q_UNUSED(error)

    if (m_task_id != id) return;

    // 置无效
    m_task_id = -1;

    // 关闭文件，做清理工作
    if (m_file.isOpen())
        m_file.close();
}

END_NAMESPACE
